package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.Dish;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.DishMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.service.ShoppingCartService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
import com.sky.entity.Setmeal;
import com.sky.mapper.SetmealMapper;

@Service

public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private SetmealMapper setmealMapper;

    /**
     * 增加购物车
     * @param shoppingCartDTO
     */
    public void addShoppingCart(ShoppingCartDTO shoppingCartDTO) {
    ShoppingCart shoppingCart=new ShoppingCart();
    BeanUtils.copyProperties(shoppingCartDTO,shoppingCart);
    shoppingCart.setUserId(BaseContext.getCurrentId());
    List<ShoppingCart> list=shoppingCartMapper.list(shoppingCart);

    if(list!=null&&list.size()>0){
        ShoppingCart res=list.get(0);
        res.setNumber(res.getNumber()+1);
        shoppingCartMapper.updateNumberById(res);
    }else {
        Long dishId = shoppingCart.getDishId();

        if(dishId!=null){
            Dish dish=dishMapper.select(dishId);
            shoppingCart.setName(dish.getName());
            shoppingCart.setAmount(dish.getPrice());
            shoppingCart.setImage(dish.getImage());
        }else {
        Long setmealId = shoppingCart.getSetmealId();
        Setmeal setmeal=setmealMapper.getById(setmealId);
        shoppingCart.setName(setmeal.getName());
        shoppingCart.setAmount(setmeal.getPrice());
        shoppingCart.setImage(setmeal.getImage());
        }
        shoppingCart.setNumber(1);
        shoppingCart.setCreateTime(LocalDateTime.now());
        shoppingCartMapper.insert(shoppingCart);
    }

    }


    public void subShoppingCart(ShoppingCartDTO shoppingCartDTO) {
        ShoppingCart shoppingCart=new ShoppingCart();
        BeanUtils.copyProperties(shoppingCartDTO,shoppingCart);
        shoppingCart.setUserId(BaseContext.getCurrentId());
        List<ShoppingCart> list=shoppingCartMapper.list(shoppingCart);

        if(list!=null&&list.size()>0){
            ShoppingCart res=list.get(0);
            Integer number = res.getNumber();

            if(number==1){
                //直接删除
                shoppingCartMapper.deleteByshoppingCart(shoppingCart);
            }else {
                //减1
                res.setNumber(res.getNumber()-1);
                shoppingCartMapper.updateNumberById(res);

            }

        }



    }

}
